package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.DtsGoodsMapper;
import com.qf.mapper.DtsGrouponRulesMapper;
import com.qf.pojo.DtsGoods;
import com.qf.pojo.DtsGrouponRules;
import com.qf.pojo.DtsUser;
import com.qf.service.DtsGoodsService;
import com.qf.service.DtsGrouponRulesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DtsGrouponRulesServiceImpl implements DtsGrouponRulesService {
    @Autowired
    DtsGrouponRulesMapper mapper;
    @Autowired
    DtsGoodsMapper goodsMapper;
    @Override
    public Map<String, Object> queryIpage(Integer page, Integer limit, Integer goodsId, String sort, String order) {
        IPage<DtsGrouponRules> iPage = new Page<>(page, limit);

        QueryWrapper<DtsGrouponRules> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(goodsId)) {
            wrapper.eq("goods_id", goodsId);
        }
        if ("desc".equals(order)){
            wrapper.orderByDesc(sort);
        }else {
            wrapper.orderByAsc(sort);
        }


        mapper.selectPage(iPage,wrapper);
        long total = iPage.getTotal();
        List<DtsGrouponRules> records = iPage.getRecords();
        Map<String, Object> data = new HashMap<>();
        data.put("total",total);
        data.put("items",records);
        return data;
    }

    @Override
    public DtsGrouponRules create(DtsGrouponRules grouponRules) {
        DtsGoods goods = goodsMapper.selectById(grouponRules.getGoodsId());
            grouponRules.setPicUrl(goods.getPicUrl());
            grouponRules.setGoodsName(goods.getName());
        grouponRules.setDeleted(false);
        grouponRules.setAddTime(new Date());
        grouponRules.setUpdateTime(new Date());

        mapper.insert(grouponRules);
        return grouponRules;
    }

    @Override
    public DtsGrouponRules update(DtsGrouponRules grouponRules) {
        DtsGoods goods = goodsMapper.selectById(grouponRules.getGoodsId());
            grouponRules.setPicUrl(goods.getPicUrl());
            grouponRules.setGoodsName(goods.getName());
        grouponRules.setDeleted(false);
        grouponRules.setUpdateTime(new Date());

        mapper.updateById(grouponRules);
        return grouponRules;
    }

    @Override
    public void delete(DtsGrouponRules grouponRules) {
        grouponRules.setDeleted(true);
        mapper.updateById(grouponRules);
    }
}